package index.btree;

import static storage.file.Page.BLOCK_SIZE;
import static storage.file.Page.INT_SIZE;
import static storage.sql.Types.INTEGER;
import storage.buffer.PageFormatter;
import storage.file.Page;
import storage.record.TableInfo;

public class BTPageFormatter implements PageFormatter {
	private TableInfo md;
	private int flag;

	public BTPageFormatter(TableInfo md, int flag) {
		this.md = md;
		this.flag = flag;
	}

	public void format(Page page) {
		page.setInt(0, flag);
		page.setInt(INT_SIZE, 0);
		int recsize = md.recordLength();
		for (int pos = 2 * INT_SIZE; pos + recsize < BLOCK_SIZE; pos += recsize)
			makeDefaultRecord(page, pos);
	}

	private void makeDefaultRecord(Page page, int pos) {
		for (String fldname : md.schema().fields()) {
			int offset = md.offset(fldname);
			if (md.schema().type(fldname) == INTEGER)
				page.setInt(pos + INT_SIZE + offset, 0);
			else
				page.setString(pos + INT_SIZE + offset, "");
		}
	}
}
